﻿/****************************************************************************
Copyright (c) 2014-2015 凌惊雪 微信:Lingjingxue 邮箱:lingjingxue@sina.com QQ:271487457

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/

using ServerBase.LunarSocket;
using ServerBase.Protocol;
using UtilLib;
using static ServerBase.Config.Conf;
using static ServerBase.Service.BaseDispatch;
using static UtilPublic.Redis.ServerRedis;
using ServerGame.Service;
using System.Collections.Generic;
using UtilPublic.ServerLoger;
using ServerBase.Service;
using ServerBase.Config;
using static ServerGame.Service.Dispatcher;
using ServerBase.Client;
using System;
using ServerPublic.Data;
using ServerGame.GameObject;
using static UtilPublic.Serialization.Jsh;
using ServerPublic.DataBaseMysql;
using UtilPublic.ApiDispatcher;
using ServerGame.Data;
using static ServerGame.Manager.Efun;
using System.Text;

namespace ServerGame.Manager
{
    public enum EAttackType
    {
        常规,
        快攻,
        反击,
        连招,
    }
    /// <summary>
    /// 管理 战斗
    /// </summary>
    public static partial class CombatMgr
    {
        //秒心跳
        public static void LoopSecond()
        {
            foreach (var room in DataGame.DictRoom.Values)
            {
                LoopSecond(room);
            }
        }
        //秒心跳
        public static void LoopSecond(Room room)
        {
            foreach (var player in room.DictPlayer.Values)
            {
                player.TryAttack();
            }
            foreach (var npc in room.DictNpc.Values)
            {
                npc.TryAttack();
            }
        }
        public static bool EnvSame(this MudChar me, MudChar ob)
        {
            return (me.Env.Uid == ob.Env.Uid); 
        }
        public static bool IsOnline(this MudChar me)
        {
            if (me.Type == EMudObjType.Player)
            {
                return ((Player)me).IsOnline;
            }
            return true;
        }
        public static void EnemyAdd(this MudChar me, MudChar victim)
        {
            if (victim.Type == EMudObjType.Player)
            {
                me.DictEnemyPlayer[victim.Uid] = victim;
            }
            else
            {
                me.DictEnemyNpc[victim.Uid] = victim;
            }
        }
        public static void EnemyRemove(this MudChar me, MudChar victim)
        {
            if (victim.Type == EMudObjType.Player)
            {
                me.DictEnemyPlayer.Remove(victim.Uid);
            }
            else
            {
                me.DictEnemyNpc.Remove(victim.Uid);
            }
        }
        //进入房间
        public static void RoomInitEnemy(this Player player)
        {
            //判断敌人
            foreach (var npc in player.Room.DictNpc.Values)
            {
                if (npc.DictEnemyPlayer.ContainsKey(player.Puid))
                {
                    MessageVision(ConfDescHurt.Values.RandomSingle().Desc, npc, player);
                    npc.IsFighting = true;
                    player.IsFighting = true;
                }
            }
        }
        //过滤敌人
        public static List<MudChar> GetEnemys(this MudChar me)
        {
            bool getEnemy(MudChar x)
            {
                return x.IsLiving
                    && me.EnvSame(x);
            }

            var list = new List<MudChar>();
            foreach (var cchar in me.DictEnemyNpc.Values)
            {
                if (getEnemy(cchar))
                {
                    list.Add(cchar);
                }
            }
            foreach (var cchar in me.DictEnemyPlayer.Values)
            {
                if (getEnemy(cchar))
                {
                    list.Add(cchar);
                }
            }
            return list;
        }
        //选择对象攻击
        public static void TryAttack(this MudChar me)
        {
            if (!me.IsFighting)
            {
                return;
            }
            if (!me.IsLiving)
            {
                me.IsFighting = false;
                return;
            }
            var list = me.GetEnemys();
            if (list.IsNullOrEmpty())
            {
                me.IsFighting = false;
                return;
            }
            var ob = list.RandomSingle();
            me.Attack(ob);
        }
        //攻击
        public static void Attack(this MudChar me, MudChar victim)
        {
            if (!me.IsOnline())
            {
                return;
            }
            if (victim.IsBusy || !victim.IsLiving)
            {
                me.IsGuarding = false;
                victim.EnemyAdd(me);
                me.DoAttack(victim, EAttackType.快攻);
                return;
            }
            var ap = me[EProp.cor];
            var dp = victim[EProp.cps];
            loger.Debug($"Attack ap{ap} dp{dp}");
            if (ap > MudRandom(dp * 2))
            {
                me.IsGuarding = false;
                victim.EnemyAdd(me);
                me.DoAttack(victim, EAttackType.常规);
                return;
            }
            if (!me.IsGuarding)
            {
                me.IsGuarding = true;
                MessageVision(ConfDescGuard.Values.RandomSingle().Desc, me, victim);
            }
        }
        //替换部位和武器
        public static void MessageVisionAttack(string msg, MudChar me, MudChar victim, string limbvictim)
        {
            var result = msg.Replace("$l", limbvictim);
            result = result.Replace("$w", me.ActWeaponName);
            result = result.Replace("$W", victim.ActWeaponName);
            MessageVision(result, me, victim);
        }
        //攻击
        public static void DoAttack(this MudChar me, MudChar victim, EAttackType attackType)
        {
            //造成伤害 -1=闪避 -2=招架
            int damage = 0;
            bool wounded = false;

            MessageVision($"{(me.IsPlayer ? "#HIR#" : "")}$N 攻击 $n {attackType}", me, victim);

            //目标部位
            var limbvictim = ConfRaceExt[victim.Race].SettBase.Limbs.RandomSingle();

            //攻击信息
            me.ActionGet();
            string msgattack = me.ActUse.Desc + "！";
            MessageVisionAttack(msgattack, me, victim, limbvictim);

            //命中
            long ap = me.PropCbt(EPropCbt.attack);
            loger.Debug($"ap {ap}");

            //判断闪躲
            long dp = victim.PropCbt(EPropCbt.dodge);
            if (victim.IsBusy)
            {
                dp = dp / 3;
            }
            dp = Math.Max(dp, 1);
            loger.Debug($"dp {dp}");
            bool bdodge = (MudRandom(ap + dp) < dp);
            //bdodge = true;
            if (bdodge)
            {
                string msgdodge;
                if (victim.ActDodgeMsgs.IsNullOrEmpty())
                {
                    msgdodge = ConfDescDodge.Values.RandomSingle().Desc;
                }
                else
                {
                    msgdodge = victim.ActDodgeMsgs.RandomSingle();
                }
                MessageVisionAttack(msgdodge, me, victim, limbvictim);

                damage = -1;
            }
            else
            {
                //判断招架
                long pp = victim.PropCbt(EPropCbt.parry);
                if (victim.IsBusy)
                {
                    pp = pp / 3;
                }
                pp = Math.Max(pp, 1);
                loger.Debug($"pp {pp}");
                bool bparry = (MudRandom(ap + pp) < pp);
                //bparry = true;
                if (bparry)
                {
                    string msgparry;
                    if (victim.ActParryMsgs.IsNullOrEmpty())
                    {
                        if (victim.ActEquipWeaponType == EWeaponType.无)
                        {
                            msgparry = ConfDescParryU.Values.RandomSingle().Desc;
                        }
                        else
                        {
                            msgparry = ConfDescParryW.Values.RandomSingle().Desc;
                        }
                    }
                    else
                    {
                        msgparry = victim.ActParryMsgs.RandomSingle();
                    }
                    MessageVisionAttack(msgparry, me, victim, limbvictim);

                    damage = -2;
                }
                else
                {
                    //伤害造成
                    damage = (int)me.PropCbt(EPropCbt.damage);
                    damage = (damage + MudRandom(damage)) / 2;
                    if (me.ActUse.Damage > 0)
                    {
                        damage = damage * me.ActUse.Damage / 100;
                    }

                    //
                    int damage_bonus = me[EProp.str];
                    if (me.ActUse.Force > 0)
                    {
                        damage_bonus = damage_bonus * me.ActUse.Force / 100;
                    }
                    if (damage_bonus > 0)
                    {
                        damage += (damage_bonus + MudRandom(damage_bonus)) / 2;
                    }
                    damage = Math.Max(damage, 0);

                    var defense_factor = victim.Exp;
                    while (MudRandom(defense_factor) > me.Exp)
                    {
                        damage -= damage / 3;
                        defense_factor /= 2;
                    }

                    damage = victim.ReceiveDamage(EProp.kee, damage, me);

                    //todo 切磋不掉上限
                    if (me.ActEquipWeaponType != EWeaponType.无
                        && MudRandom(damage) > victim[EProp.armor])
                    {
                        victim.ReceiveWound(EProp.efkee, damage - victim[EProp.armor], me);
                        wounded = true;
                    }

                    string msgdamage = DamageMsg(damage, me.ActUse.DamageType);
                    MessageVisionAttack(msgdamage, me, victim, limbvictim);

                }
            }
            loger.Debug($"damage {damage}");
            if (damage > 0)
            {
                ReportStatus(victim, wounded);
            }


        }
    }
}
